package com.tanhua.sso.service;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.servcie.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    /**
     * 保存用户信息
     * @param map
     * @param token
     * @return
     */
    public Boolean saveUserInfo(Map<String, String> map, String token) {
        //校验token
        User user = userService.queryUserByToken(token);
        //如果user为null, 则表示保存失败
        if (null == user){
            return false;
        }
        //不为null, 则保存用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsIgnoreCase(map.get("gender"),"man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(map.get("nickname"));
        userInfo.setBirthday(map.get("birthday"));
        userInfo.setCity(map.get("city"));

        return userInfoMapper.insert(userInfo) == 1;
    }

    public Boolean saveUserLogo(MultipartFile file, String token) {
        //校验token
        User user = userService.queryUserByToken(token);
        //如果user为null, 则表示保存失败
        if (null == user){
            return false;
        }
        try {
            //校验图片是否是人像, 如果不是则返回false
            boolean flag = faceEngineService.checkIsPortrait(file.getBytes());
            if (!flag){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //图片上传阿里云oss
        PicUploadResult result = picUploadService.upload(file);
        //如果为空, 则表示上传失败
        if (StringUtils.isEmpty(result.getName())){
            //上传失败
            return false;
        }
        //保存用户头像到用户表中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",user.getId());
        return userInfoMapper.update(userInfo,wrapper) == 1;
    }
}
